package com.fany.filesearcher;

import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import com.fany.constants.StringResources;
import com.fany.utils.CommonUtils;

public class FileLoadController
{
    private Context _context;
    private FileSearchHandler _searchHandler;
    private FileSearchThread _searchThread;
    private FileSearchProgressThread _progressThread;
    private FileSearchProgressHandler _progressHandler;

    public FileLoadController(Context context, SQLiteFileRecorder recorder)
    {
        _context = context;

        _searchHandler = new FileSearchHandler();
        _searchThread = new FileSearchThread(_context.getApplicationContext(), _searchHandler);
        _searchHandler.fileSearchThread = _searchThread;

        _progressThread = new FileSearchProgressThread();
        _progressHandler = new FileSearchProgressHandler(recorder, _progressThread);
        _progressThread.handler = _progressHandler;
    }

    public void loadFiles()
    {
        final ProgressDialog pd = ProgressDialog.show(_context, "加载数据", "正在清理缓存...");
        pd.setOnKeyListener(new DialogInterface.OnKeyListener()
        {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
            {
                if ((event.getKeyCode() == KeyEvent.KEYCODE_BACK) &&(event.getAction() == KeyEvent.ACTION_UP))
                {
                    CommonUtils.confirm(_context, StringResources.Hint, "确定要取消当前操作？",
                            new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    _searchHandler.interrupt();
                                    pd.setMessage(StringResources.IsCanceling);
                                }
                            });
                    return true;
                }
                return false;
            }
        });

        _searchHandler.progressDialog = pd;
        _progressHandler.progressDialog = pd;

        new Thread(_progressThread).start();
        new Thread(_searchThread).start();
    }
}
